package com.taritari.journal.utils;

import org.springframework.stereotype.Component;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

/**
 * @author taritari
 * @date 2024-05-11 15:04
 * @description
 */
@Component
public class IkAnalyzerUtils {
    /**
     * 拆分词云
     *
     * @param list     需要拆分的词云集合
     * @param quantity 结果集取的数量
     */
    public static String wordCloudParsing(List<String> list, Integer quantity) {
        Map<String,Integer> result = wordCloud(list,quantity);
        StringBuilder str = new StringBuilder();
        result.forEach((k, v) -> {
            String value = " " + k;
            str.append(value);
        });
        return str.toString().trim();
    }

    /**
     * 拆分词云
     *
     * @param list     需要拆分的词云集合
     * @param quantity 结果集取的数量
     */
    public static List<Map<String,Object>> wordCloudList(List<String> list, Integer quantity) {
        Map<String,Integer> result = wordCloud(list,quantity);
        List<Map<String,Object>> mapList = new LinkedList<>();
        result.forEach((k, v) -> {
            Map<String,Object> map = new HashMap<>(16);
            map.put("name",k);
            map.put("value",v);
            mapList.add(map);
        });
        Collections.reverse(mapList);
        return mapList;
    }

    /**
     * 拆分词云
     *
     * @param list     需要拆分的词云集合
     * @param quantity 结果集取的数量
     */
    public static Map<String,Integer> wordCloud(List<String> list, Integer quantity) {
        StringReader reader = new StringReader(String.join(",", list));
        IKSegmenter ikSegmenter = new IKSegmenter(reader, true);
        Map<String, Integer> map = null;
        try {
            Lexeme lexeme;
            map = new HashMap<>(16);
            while ((lexeme = ikSegmenter.next()) != null) {
                String str = lexeme.getLexemeText();
                Integer num = map.get(str);
                if (num != null && num > 0) {
                    map.put(str, num + 1);
                } else {
                    map.put(str, 1);
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Integer> result = new LinkedHashMap<>();
        if (quantity != null && quantity > 0) {
            map.entrySet().stream().sorted(Map.Entry.comparingByValue()).limit(quantity)
                    .forEachOrdered(item -> result.put(item.getKey(), item.getValue()));
        } else {
            map.entrySet().stream().sorted(Map.Entry.comparingByValue())
                    .forEachOrdered(item -> result.put(item.getKey(), item.getValue()));
        }
        return result;
    }

}
